<template>
  <view>
    <uni-search-bar @confirm="search" style="margin-bottom: -14upx;" :focus="true" readonly v-model="searchValue" @click="onClickSearch" />
    <uni-popup ref="popupSearch" type="top" class="userPopup">
      <view class="popup-body">
        <uni-forms
          ref="searchFormRef"
          v-model="formData"
          :rules="rules"
          label-position="top"
          label-width="75vw"
          class="form">
          <uni-forms-item name="billNumber" label="作业票据号">
            <uni-easyinput type="text" v-model="formData.billNumber" placeholder="请输入作业票据号" />
          </uni-forms-item>
          <uni-forms-item name="jobType" label="作业类型">
            <!-- <uni-easyinput type="text" v-model="formData.jobType" placeholder="请输入作业类型" /> -->
            <uni-data-select
              v-model="formData.jobType"
              :localdata="jobTypeList"
              :clear="false"
              placeholder="请选择作业类型">
            </uni-data-select>
          </uni-forms-item>
          <uni-forms-item name="planStartDate" label="开始时间">
            <uni-datetime-picker
              v-model="formData.planStartDate"
              placeholder="请选择开始时间"
              type="datetime"
              :hide-second="true"
              @change="changeTime">
            </uni-datetime-picker>
          </uni-forms-item>
          <uni-forms-item name="planEndDate" label="结束时间">
            <uni-datetime-picker
              v-model="formData.planEndDate"
              placeholder="请选择结束时间"
              type="datetime"
              :hide-second="true"
              @change="changeTime">
            </uni-datetime-picker>
          </uni-forms-item>

          <div class="ft">
            <button type="info" class="reset" @click="handleReset">重置</button>
            <button type="primary" @click="handleSubmit">搜索</button>
          </div>
        </uni-forms>
      </view>
    </uni-popup>
    
    <Table ref="table" :fetchData="fetchData">
      <template #default="{ data }">
        <view v-for="item in data">
          <uni-card v-if="item.id !== activeId" @click="onCardClick(item)">
            <template #title> </template>
            <view class="uni-body">
              <view class="title">
                <view class="title-left">
                  <view class="title-title">
                    {{ item.billNumber }}
                  </view>
                  <view class="title-times">
                    {{ item.applyPeople }}
                  </view>
                  <view
                    class="title-state"
                    :style="{
                      backgroundColor: getSplc(item)? 'rgb(226,240,217)' : 'rgb(248,240,235)',
                      color: getSplc(item)? 'rgb(0,176,80)': 'rgb(197,90,17)' ,
                    }"
                  >
                    {{ getSplc(item)? '已关闭' : '办理中'}}
                  </view>
                </view>
              </view>
              <view>
                {{ item.jobContent }}
              </view>
              <view
                style="
                  font-size: 12px;
                  display: flex;
                  justify-content: space-between;
                  width: 100%;
                "
              >
                <text style="color: orange">
                  {{ item.jobPlanStartDate + "  " + item.jobPlanStartTime }}
                </text>
                <text style="flex: end">
                  {{ item.workShop }}
                </text>
              </view>
            </view>
            <!-- <view class="uni-body">
              <text style="color: red; font-size: 12px">
                {{ item.jobPlanStartDate + "  " + item.jobPlanStartTime }}
              </text>
            </view> -->
          </uni-card>
          <uni-card v-else>
            <view class="button-box">
              <uni-icons
                type="closeempty"
                class="close"
                size="30"
                @click="closeButton"
              ></uni-icons>
              <button
                class="mini-btn"
                type="primary"
                size="mini"
                @click="onListClick"
                v-hasPermi="['zyp-list']"
                style="width: 30%"
              >
                作业票列表
              </button>
              <button
                class="mini-btn"
                type="primary"
                @click="openPopup"
                size="mini"
                v-hasPermi="['add:zyp']"
                style="width: 30%"
                v-if="!isExpire()"
              >
                新开作业票
              </button>
              <button
                class="mini-btn"
                type="primary"
                @click="openXuqian"
                size="mini"
                style="width: 30%"
                v-hasPermi="['zyp-xq']"
              >
                续签
              </button>
              <button
                class="mini-btn"
                type="warn"
                :style="{
                  backgroundColor:
                    selectRow.operateStatus == 1 ? '#e64340' : '#e6a23c',
                  color: '#ffffff',
                }"
                @click="openstop"
                size="mini"
                v-if="!isExpire()"
                style="width: 30%"
              >
                {{ selectRow.operateStatus == 1 ? "恢复" : "暂停" }}
              </button>
              <button
                class="mini-btn"
                type="primary"
                @click="openChange"
                size="mini"
                style="width: 30%"
                :style="{
                  backgroundColor: '#e6a23c',
                  color: '#ffffff',
                }"
              >
                变更监护人
              </button>
            </view>
          </uni-card>
        </view>
      </template>
    </Table>
    <uni-popup ref="popup" background-color="#fff" @change="() => {}">
      <uni-card>
        <view>
          <button
            v-for="item in showZypList"
            class="mini-btn"
            type="text"
            @click="toCreateBill(item.type)"
            size="mini"
          >
            {{ item.name }}
          </button>
        </view>
      </uni-card>
    </uni-popup>
    <uni-popup ref="stopPopup" background-color="#fff">
      <uni-card v-if="stopForm.currentStatus == 1">
        <uni-forms
          ref="formRef"
          label-position="top"
          :model="stopForm"
          label-width="75vw"
        >
          <template v-for="item in stopOptions">
            <uni-forms-item
              :label="item.label"
              :required="item.required"
              :rules="
                item.required
                  ? [
                      {
                        required: true,
                        errorMessage: '字段为必填项',
                      },
                    ]
                  : []
              "
              :name="item.prop"
            >
              <uni-easyinput
                :style="{
                  border: 'none',
                }"
                v-if="item.type == 'input'"
                type="text"
                v-model="stopForm[item.prop]"
              />

              <uni-datetime-picker
                v-else-if="
                  [
                    'datetime',
                    'date',
                    'datetimerange',
                    'daterange',
                    'time',
                  ].includes(item.type)
                "
                :type="item.type"
                v-model="stopForm[item.prop]"
              />
            </uni-forms-item>
          </template>
        </uni-forms>
        <button type="primary" @click="submitStopForm">提 交</button>
      </uni-card>
      <uni-card v-if="stopForm.currentStatus == 2">
        <view style="margin-bottom: 30upx">
          {{
            `本次作业暂停时间${hfText}，即将恢复作业，请确认人员到位、安全措施落实`
          }}
        </view>
        <view style="width: 75vw; display: flex; justify-content: space-around">
          <button type="" size="mini" @click="close">取 消</button>
          <button type="primary" size="mini" @click="submitRestartForm">
            确 认
          </button>
        </view>
      </uni-card>
    </uni-popup>
    <uni-popup ref="xuqianPopup" background-color="#fff">
      <uni-card>
        <uni-forms
          ref="xuqianRef"
          label-position="top"
          :model="xuqianForm"
          label-width="75vw"
        >
          <template v-for="item in xuqianOptions">
            <uni-forms-item
              :label="item.label"
              :required="item.required"
              :rules="
                item.required
                  ? [
                      {
                        required: true,
                        errorMessage: '字段为必填项',
                      },
                    ]
                  : []
              "
              :name="item.prop"
            >
              <uni-easyinput
                :style="{
                  border: 'none',
                }"
                v-if="item.type == 'input'"
                type="text"
                v-model="xuqianForm[item.prop]"
              />

              <uni-datetime-picker
                v-else-if="
                  [
                    'datetime',
                    'date',
                    'datetimerange',
                    'daterange',
                    'time',
                  ].includes(item.type)
                "
                :type="item.type"
                v-model="xuqianForm[item.prop]"
              />
              <uni-data-select
                style="border: none"
                v-else-if="item.type == 'select'"
                v-model="xuqianForm[item.prop]"
                :localdata="item.optionItems"
              ></uni-data-select>
            </uni-forms-item>
          </template>
        </uni-forms>
        <button type="primary" @click="submitXuqianForm">提 交</button>
      </uni-card>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed } from "vue";
import Table from "@/components/uniList.vue";
import { useAsyncData } from "@/hooks/useAsyncData.js";
import { apis as APIS, stopAndRestart } from "@/api/zygl/zyjh.js";
import { onLaunch, onShow, onHide } from "@dcloudio/uni-app";

import { router } from "@/router/index.js";
import { PATH } from "../paths";
const zypTypes = [
  {
    name: "吊装安全作业票",
    type: "1",
    keyWord: "吊装",
  },
  {
    name: "动火安全作业票",
    type: "2",
    keyWord: "动火",
  },
  {
    name: "高处安全作业票",
    type: "3",
    keyWord: "高处",
  },
  {
    name: "动土安全作业票",
    type: "4",
    keyWord: "动土",
  },
  {
    name: "临时用电作业票",
    type: "5",
    keyWord: "用电",
  },
  {
    name: "动用射线安全作业票",
    type: "6",
    keyWord: "射线",
  },
  {
    name: "断路安全作业票",
    type: "7",
    keyWord: "断路",
  },
  {
    name: "盲板抽堵安全作业票",
    type: "8",
    keyWord: "盲板",
  },
  {
    name: "设备开孔安全作业票",
    type: "9",
    keyWord: "设备",
  },
  {
    name: "受限空间安全作业票",
    type: "10",
    keyWord: "受限空间",
  },
];

const showZypList = computed(() => {
  let zypList = zypTypes.filter((item) =>
    useZypType.value.includes(item.keyWord)
  );
  if (zypList.length == 0) {
    return zypTypes;
  } else {
    return zypList;
  }
});
const useZypType = ref([]);
const activeId = ref("");
const selectRow = ref({});
const popup = ref();
const openPopup = () => {
  popup.value.open("center");
};
const onCardClick = (item) => {
  useZypType.value = item.jobType;
  activeId.value = item.id;
  selectRow.value = item;
};

const onListClick = () => {
  router.toPage({
    path: PATH.SONLIST,
    params: {
      pid: selectRow.value.billNumber,
      id: activeId.value,
    },
  });
};

const toCreateBill = (billType) => {
  APIS.creatBillNum({
    billType,
  }).then((res) => {
    router.toPage({
      // path: billType == 2 ? PATH.ZYPV2 : PATH.ZYP,
      path: PATH.ZYP,
      params: {
        num: res.msg,
        billNumber: selectRow.value.billNumber,
        billType,
        pid: activeId.value,
      },
    });
  });
};
const closeButton = () => {
  activeId.value = "";
};
const table = ref();

const searchFormRef = ref(null);
const formData = ref({
  billNumber: '',
  jobType: '',
  planStartDate: '',
  planEndDate: ''
})
const searchValue = ref()
const popupSearch = ref();

// 作业类型
const jobTypeList = ref([
  {
    value: '动火作业',
    text: '动火作业'
  },
  {
    value: '设备开孔作业',
    text: '设备开孔作业'
  },
  {
    value: '高处作业',
    text: '高处作业'
  },
  {
    value: '临时用电作业',
    text: '临时用电作业'
  },
  {
    value: '受限空间作业',
    text: '受限空间作业'
  },
  {
    value: '断路作业',
    text: '断路作业'
  },
  {
    value: '盲板抽堵作业',
    text: '盲板抽堵作业'
  },
  {
    value: '动土作业',
    text: '动土作业'
  },
  {
    value: '吊装作业',
    text: '吊装作业'
  },
  {
    value: '动用射线作业',
    text: '动用射线作业'
  }
])

const filterForm = ref({
  billNumber: formData.value.billNumber,
  jobType: formData.value.jobType,
  planStartDate: formData.value.planStartDate,
  planEndDate: formData.value.planEndDate
});

const { fetchData, getList, queryParams } = useAsyncData({
  table,
  APIS,
  filterForm: filterForm.value
});
onShow(() => {
  // getList();
});


const onClickSearch = () => {
  popupSearch.value.open();
}

// 搜索
const handleSubmit = () => {
  filterForm.value.billNumber = formData.value.billNumber
  filterForm.value.jobType = formData.value.jobType
  filterForm.value.planStartDate = formData.value.planStartDate
  filterForm.value.planEndDate = formData.value.planEndDate
  
  getList();
  popupSearch.value.close();
}

// 重置
const handleReset = () => {
  formData.value = {
    billNumber: null,
    jobType: null,
    planStartDate: null,
    planEndDate: null
  }
  filterForm.value.billNumber = ''
  filterForm.value.jobType = ''
  filterForm.value.planStartDate = ''
  filterForm.value.planEndDate = ''
  
  // popup.value.close();
  getList();
}


const isExpire = (row) => {
  const planTime = Date.parse(
    selectRow.value.jobPlanEndDate + " " + selectRow.value.jobPlanEndTime
  );
  const nowDate = Date.now();
  if (nowDate > planTime) {
    return true;
  }
  return false;
};
// 暂停逻辑
const stopOptions = [
  // {
  //   label: "时间",
  //   optionItems: [],
  //   prop: "operateTime",
  //   type: "datetime",
  //   required: true,
  // },
  {
    label: "暂停描述",
    optionItems: [],
    prop: "remark",
    type: "input",
    required: true,
  },
];
const stopForm = ref({});
const stopPopup = ref();
const hfText = ref(20);
const openstop = () => {
  stopForm.value.pid = selectRow.value.id;
  stopForm.value.operateStatus = selectRow.value.operateStatus;
  stopForm.value.currentStatus = selectRow.value.operateStatus == 1 ? 2 : 1;
  const nowTime = Date.now();
  const stopTime = Date.parse(selectRow.value.operateDate);
  let min = ((nowTime - stopTime) / 1000 / 60).toFixed(0);
  const hour = (min / 60).toFixed(0);
  const smin = min % 60;
  if (hour == 0 && smin == 0) {
    hfText.value = "1分钟";
  } else if (hour > 0) {
    hfText.value = `${hour}小时${smin}分钟`;
  } else {
    hfText.value = `${smin}分钟`;
  }
  stopPopup.value.open("center");
};
const formRef = ref();
const submitStopForm = async () => {
  const res = await formRef.value.validate();
  stopAndRestart
    .add({
      ...stopForm.value,
      operateTime: formatDate(new Date()),
    })
    .then((res) => {
      stopPopup.value.close();
      getList();
      activeId.value = "";
      selectRow.value = {};
      stopForm.value = {};
      uni.showToast({
        title: "操作成功",
      });
    });
};
function padZero(n) {
  return n < 10 ? "0" + n : n;
}
const formatDate = (time) => {
  if (time) {
    const date = new Date(time);
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const h = date.getHours();
    const m = date.getMinutes();
    const s = date.getSeconds();
    return `${year}-${padZero(month)}-${padZero(day)} ${padZero(h)}:${padZero(
      m
    )}:${padZero(s)}`;
  } else {
    return null;
  }
};
const submitRestartForm = async () => {
  stopAndRestart
    .add({
      ...stopForm.value,
      operateTime: formatDate(new Date()),
    })
    .then((res) => {
      stopPopup.value.close();
      getList();
      activeId.value = "";
      selectRow.value = {};
      uni.showToast({
        title: "操作成功",
      });
    });
};
const close = () => {
  stopPopup.value.close();
};

// 跳转变更监护人
const openChange = () => {
  router.toPage({
    path: "/pages/zygl/zyxkbl/components/bgjhr",
    params: {
      pid: activeId.value,
      isExpire: !isExpire(),
    },
  });
};

// 续签逻辑
const xuqianForm = ref({});
const xuqianPopup = ref();
const xuqianRef = ref();
const optionItems = [
  { value: "00:00", text: "00:00" },
  { value: "00:30", text: "00:30" },
  { value: "01:00", text: "01:00" },
  { value: "01:30", text: "01:30" },
  { value: "02:00", text: "02:00" },
  { value: "02:30", text: "02:30" },
  { value: "03:00", text: "03:00" },
  { value: "03:30", text: "03:30" },
  { value: "04:00", text: "04:00" },
  { value: "04:30", text: "04:30" },
  { value: "05:00", text: "05:00" },
  { value: "05:30", text: "05:30" },
  { value: "06:00", text: "06:00" },
  { value: "06:30", text: "06:30" },
  { value: "07:00", text: "07:00" },
  { value: "07:30", text: "07:30" },
  { value: "08:00", text: "08:00" },
  { value: "08:30", text: "08:30" },
  { value: "09:00", text: "09:00" },
  { value: "09:30", text: "09:30" },
  { value: "10:00", text: "10:00" },
  { value: "10:30", text: "10:30" },
  { value: "11:00", text: "11:00" },
  { value: "11:30", text: "11:30" },
  { value: "12:00", text: "12:00" },
  { value: "12:30", text: "12:30" },
  { value: "13:00", text: "13:00" },
  { value: "13:30", text: "13:30" },
  { value: "14:00", text: "14:00" },
  { value: "14:30", text: "14:30" },
  { value: "15:00", text: "15:00" },
  { value: "15:30", text: "15:30" },
  { value: "16:00", text: "16:00" },
  { value: "16:30", text: "16:30" },
  { value: "17:00", text: "17:00" },
  { value: "17:30", text: "17:30" },
  { value: "18:00", text: "18:00" },
  { value: "18:30", text: "18:30" },
  { value: "19:00", text: "19:00" },
  { value: "19:30", text: "19:30" },
  { value: "20:00", text: "20:00" },
  { value: "20:30", text: "20:30" },
  { value: "21:00", text: "21:00" },
  { value: "21:30", text: "21:30" },
  { value: "22:00", text: "22:00" },
  { value: "22:30", text: "22:30" },
  { value: "23:00", text: "23:00" },
  { value: "23:30", text: "23:30" },
];
const xuqianOptions = [
  {
    label: "作业开始时间",
    optionItems: optionItems,
    prop: "jobPlanStartTime",
    type: "select",
    required: true,
  },
  {
    label: "作业结束时间",
    optionItems: optionItems,
    prop: "jobPlanEndTime",
    type: "select",
    required: true,
  },
  {
    label: "作业开始日期",
    optionItems: [],
    prop: "jobPlanStartDate",
    type: "date",
    required: true,
  },
  {
    label: "作业结束日期",
    optionItems: [],
    prop: "jobPlanEndDate",
    type: "date",
    required: true,
  },
];
const openXuqian = () => {
  xuqianForm.value.id = selectRow.value.id;

  xuqianPopup.value.open("center");
};
const submitXuqianForm = async () => {
  const res = await xuqianRef.value.validate();
  APIS.renewal(xuqianForm.value).then((res) => {
    xuqianPopup.value.close();
    getList();
    activeId.value = "";
    selectRow.value = {};
    xuqianForm.value = {};
    uni.showToast({
      title: "操作成功",
    });
  });
};

const getSplc = (data) => {
 const planTime = Date.parse(
   data.jobPlanEndDate + " " + data.jobPlanEndTime
 );
 const nowDate = Date.now();
 if (nowDate > planTime) {
   return true;
 }
 return false;
};
</script>

<style lang="scss" scoped>
.button-box {
  // display: flex;
  position: relative;
  flex-wrap: wrap;
  justify-content: start;
  .mini-btn {
    margin: 0 5upx;
    padding: 0;
    font-size: 24upx;
  }
}
.close {
  position: absolute;
  top: -20upx;
  right: -40upx;
  color: skyblue !important;
}
.title {
  display: flex;
  justify-content: space-between;
  position: relative;
  &-left {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
  }
  &-title {
    font-weight: 600;
  }
  &-times {
    background-color: rgb(22, 119, 255);
    padding: 2px;
    font-size: 12px;
    line-height: 15px;
    border-top-left-radius: 10px;
    border-bottom-right-radius: 10px;
    margin-left: 5px;
    color: #fff;
  }

  &-state {
    // background-color: orange;
    position: absolute;
    right: 0;
    padding: 2px 5px;
    font-size: 12px;
    line-height: 15px;
    border-radius: 10px;
    margin-left: 5px;
  }
}

.popup-body{
  width: 100%;
  height: 820upx;
  padding: 20upx 30upx;
  background-color: #fff;
  
  .uni-forms-item{
    margin-bottom: 10upx;
  }

  .ft{
    display: flex;
    padding-top: 37upx;

    uni-button{
      flex: 1;
      font-size: 28upx;
    }

    .reset{
      margin-right: 50upx;
    }
  }
}
</style>
